<?php
/**
 * Configuration
 * 
 * @author Mathieu Pheulpin - sokaru91@gmail.com
 *
 */
class Mac_Configuration
{
    protected static $configuration = array();
    
    public static function load($file)
    {
        $config_dir_path = ROOT_PATH.'/config';
        if (!is_dir($config_dir_path)) {
            throw new Mac_Configuration_Exception_DirectoryNotFound('config folder count not be found');
        }
        $file_path = $config_dir_path.'/'.$file.'.php';
        if (is_file($file_path)) {
            $config = include $file_path;
            foreach ($config as $key => $value) {
                self::$configuration[$file][$key] = $value;
            }
        } else {
            throw new Mac_Configuration_Exception_Unknown_File('Trying to get configuration value in an unknown file : \''.$file.'.php\'');
        }
    }
    
    public static function get ($file, $key, $subkey = null)
    {
        if (!isset(self::$configuration[$file])) {
            self::load($file);
        }
        if (!isset(self::$configuration[$file][$key])) {
            throw new Mac_Configuration_Exception_Unknown_Key('Trying to get configuration value at an unknown key : \''.$key.'\', in \''.$file.'.php\' file');
        }
        $value = self::$configuration[$file][$key];
        if ($subkey !== null) {
            if (!is_array($value)) {
                throw new Mac_Configuration_Exception_Unknown_Subkey('Trying to get subkey \''.$subkey.'\' of the non array key \''.$key.'\'');
            } elseif (!isset($value[$subkey])) {
                throw new Mac_Configuration_Exception_Unknown_Key('Trying to get configuration value at an unknown subkey : \''.$subkey.'\', located at \''.$key.'\' key in \''.$file.'.php\' file');
            }
            $return = $value[$subkey];
        } else {
            $return = $value;
        }
        return $return;
    }
    
    public static function exists ($file, $key, $subkey = null)
    {
        if (!isset(self::$configuration[$file])) {
            self::load($file);
        }
        if ($subkey === null) {
            return isset(self::$configuration[$file][$key]);
        } else {
            return isset(self::$configuration[$file][$key][$subkey]);
        }
    }
}